package cn.itlaobing.web.servlet;

import cn.itlaobing.exception.MyException;
import cn.itlaobing.model.MsgTokenModel;
import cn.itlaobing.model.UsersModel;
import cn.itlaobing.service.RegisterService;
import cn.itlaobing.web.annotation.RequestMapping;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Random;

/**
 * Created by Administrator on 2017-11-15.
 */
@WebServlet("/register/*")
public class RegisterServlet extends BaseServlet {
    private RegisterService registerService=new RegisterService();
    //生成手机验证码
    @RequestMapping("/buildPhonePassword")
    public void buildPhonePassword(HttpServletRequest request, HttpServletResponse response)
    {
        String phone=request.getParameter("phone");
        StringBuffer sb=new StringBuffer();
        for(int i=0;i<6;i++)
        {
            int r=(int)(Math.random()*10);
            sb.append(r);
        }
        logger.info(sb.toString());
        //request.getSession().setAttribute("BUILDPHONEPASSORD",sb.toString());
        //验证码已生成，放到model中
        MsgTokenModel msgTokenModel=new MsgTokenModel();
        msgTokenModel.setPhone(phone);
        msgTokenModel.setIdentifyCode(sb.toString());
        Long l=System.currentTimeMillis();
        msgTokenModel.setTime(l);
        request.getSession().setAttribute("MSGTOKENMODEL",msgTokenModel);

    }
    //接受页面提交的全部信息（手机号，密码，以及确认密码，图片验证码，短信验证码）
    @RequestMapping("/register")
    public void register(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        String phone=request.getParameter("username");
        String password=request.getParameter("password");
        String rqpwd=request.getParameter("rqpwd");
        String imgNumber=request.getParameter("imgNumber");
        String dxyzm=request.getParameter("dxyzm");
        MsgTokenModel  msgTokenModel=(MsgTokenModel) request.getSession().getAttribute("MSGTOKENMODEL");
        //判断session中有没有值，也就是用户有没有点击获取手机验证码
        if(msgTokenModel==null)
        {
            request.getRequestDispatcher("/WEB-INF/views/order/login/register.jsp").forward(request,response);
            return ;
        }
        Long l1=System.currentTimeMillis();
        Long l2=msgTokenModel.getTime();
        //判断是否为空
        if(phone==null||"".equals(phone)||password==null||"".equals(password)
                ||rqpwd==null||"".equals(rqpwd)||imgNumber==null||"".equals(imgNumber)||dxyzm==null||"".equals(dxyzm))
        {
            request.getRequestDispatcher("/WEB-INF/views/order/login/register.jsp").forward(request,response);
            return ;
        }
        //至少全部信息均输入了
        //判断手机验证码是否过期，用户输入之后提交的时间是否和产生验证码的时间相差小于5分钟，注意
        Long time=l1-l2;
        if(time>=5*60*1000)
        //if(time>=2000)
        {
            //表示超过有效期，则返回界面重新申请
            logger.info("验证码以过期");
            request.getRequestDispatcher("/WEB-INF/views/order/login/register.jsp").forward(request,response);
            return ;
        }
        else
        {
            //验证码有效
            //得到当前 用户的手机号，判断是否一致
            if(!phone.equals(msgTokenModel.getPhone()))
            {
                //用户信息手机号和验证码发送手机号不一致，不允许
                request.getRequestDispatcher("/WEB-INF/views/order/login/register.jsp").forward(request,response);
                return ;
            }
            else
            {
                //手机号也一致，判断两次密码一致
                if(!password.equals(rqpwd))
                {
                    //用户名两次密码输入不一致，返回界面
                    request.getRequestDispatcher("/WEB-INF/views/order/login/register.jsp").forward(request,response);
                    return ;
                }
                else
                {
                    //密码相同，判断谷歌验证码是否和界面显示的相同
                    String number = (String)request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
                    logger.info("谷歌验证码"+number);
                    if(!imgNumber.equals(number))
                    {
                        //验证码不一致，返回界面
                        request.getRequestDispatcher("/WEB-INF/views/order/login/register.jsp").forward(request,response);
                        return ;
                    }
                    else
                    {
                        //谷歌验证码相同，验证短信验证码
                        if(!dxyzm.equalsIgnoreCase(msgTokenModel.getIdentifyCode()))
                        {
                            //手机验证码错误，重新返回界面注册
                            request.getRequestDispatcher("/WEB-INF/views/order/login/register.jsp").forward(request,response);
                            return ;
                        }
                        else
                        {
                            //手机验证码正确，开始注册
                            // 用户注册信息只有手机号，密码，创建时间
                            UsersModel usersModel=new UsersModel();
                            usersModel.setUserAccount(phone);
                            usersModel.setUserPassword(password);
                            usersModel.setUserRegDateTime(new Date());
                            int r=0;
                            try {
                                r=registerService.Register(usersModel);
                            } catch (MyException e) {
                                e.printStackTrace();
                            }
                            if(r>0)
                            {
                                //注册成功，跳转到登录界面
                                request.getRequestDispatcher("/WEB-INF/views/order/login/login.jsp").forward(request,response);
                                return;
                            }
                            else
                            {
                                //注册失败，跳转到注册界面
                                request.getRequestDispatcher("/WEB-INF/views/order/login/register.jsp").forward(request,response);
                                return ;
                            }
                        }

                    }

                }
            }
        }
    }
    //验证手机号是否被注册
    @RequestMapping("/isRegister")
    public void isRegister(HttpServletRequest request,HttpServletResponse response) throws IOException {
        String phone=request.getParameter("phone");
        logger.info(phone);
        Boolean flag=false;
        try {
            flag=registerService.isRegister(phone);
        } catch (MyException e) {
            e.printStackTrace();
        }
        logger.info(flag);
        PrintWriter out=response.getWriter();
        if(flag)
        {
              out.println(1);
        }
        else
        {
            out.println(0);
        }
        out.close();
    }
    //验证手机号是否被注册
    //手机号验证完后进行后台登录
    @RequestMapping("/login")
    public void login(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
        String username=request.getParameter("username");
        String password=request.getParameter("password");
        String imgNumber=request.getParameter("imgNumber");
        //得到谷歌验证码并判断是否相同
        String number = (String)request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
        if (!imgNumber.equalsIgnoreCase(number)) {
            //不相同返回登录界面
            request.getRequestDispatcher("/WEB-INF/views/order/login/login.jsp").forward(request,response);
            return;
        }
        else
        {
            //成功进入下一步操作
            UsersModel usersModel=null;
            try {
                usersModel=registerService.login(username,password);
            } catch (MyException e) {
                e.printStackTrace();
            }
            //判断是否为空，为空跳转到登录界面
            //不为空则进行修改登录时间，和登录次数修改前先要放到session中，然后进行修改
           if(username==null)
           {
               request.getRequestDispatcher("/WEB-INF/views/order/login/login.jsp").forward(request,response);
               return;
           }
           else
           {
               //用户已存在
               int r=0;
               try {
                   r=registerService.updateLastTime((usersModel.getUserLoginCount().intValue()+1),usersModel.getUserId().intValue());
               } catch (MyException e) {
                   e.printStackTrace();
               }
               if(r>0)
               {
                   //修改成功
                   request.getSession().setAttribute("USERMODEL_REQUEST",usersModel);
                   response.sendRedirect("/home/nishuone");
                   return ;
               }
               else
               {
                   //修改失败
                   request.getRequestDispatcher("/WEB-INF/views/order/login/login.jsp").forward(request,response);
                   return;
               }
           }
        }
    }

}

